<?php

// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
// 应用公共文件

use app\common\service\NodeService;
use think\Db;
use think\Request;
use app\common\service\AuthService;
use think\facade\Cache;

if (!function_exists('check_login')) {

    /**
     * 检测前端用户是否登录
     */
    function check_login()
    {
        if (empty(session('user'))) {
            return false;
        } else {
            return true;
        }
    }

}

if (!function_exists('auth')) {

    /**
     * 权限节点判断
     * @param $node 节点
     * @return bool （true：有权限，false：无权限）
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    function auth($node)
    {
        return AuthService::checkNode($node);
    }

}

if (!function_exists('parseNodeStr')) {

    /**
     * 驼峰转下划线规则
     * @param string $node
     * @return string
     */
    function parseNodeStr($node)
    {
        $tmp = [];
        foreach (explode('/', $node) as $name) {
            $tmp[] = strtolower(trim(preg_replace("/[A-Z]/", "_\\0", $name), "_"));
        }
        return trim(join('/', $tmp), '/');
    }

}

if (!function_exists('password')) {

    /**
     * 密码加密算法
     * @param $value 需要加密的值
     * @param $type  加密类型，默认为md5 （md5, hash）
     * @return mixed
     */
    function password($value)
    {
        $value = sha1('blog_') . md5($value) . md5('_encrypt') . sha1($value);
        return sha1($value);
    }

}

if (!function_exists('__buildData')) {

    /**
     * 构建数据
     * @param $data   模型数据
     * @param $method 模型方法
     */
    function __buildData(&$data, $method)
    {
        foreach ($data as &$vo) {
            $vo->$method;
        }
    }

}

if (!function_exists('alert')) {

    /**
     * 弹出层提示
     * @param string $msg 提示信息
     * @param string $url 跳转链接
     * @param int $time 停留时间 默认2秒
     * @param int $icon 提示图标
     * @return string
     */
    function alert($msg = '', $url = '', $time = 3, $icon = 6)
    {
        $success = '<meta name="renderer" content="webkit">';
        $success .= '<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">';
        $success .= '<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">';
        $success .= '<script type="text/javascript" src="/static/plugs/jquery/jquery-2.2.4.min.js"></script>';
        $success .= '<script type="text/javascript" src="/static/plugs/layui-layer/layer.js"></script>';
        if (empty($url)) {
            $success .= '<script>$(function(){layer.msg("' . $msg . '", {icon: ' . $icon . ', time: ' . ($time * 1000) . '});})</script>';
        } else {
            $success .= '<script>$(function(){layer.msg("' . $msg . '",{icon:' . $icon . ',time:' . ($time * 1000) . '});setTimeout(function(){self.location.href="' . $url . '"},2000)});</script>';
        }
        return $success;
    }

}

if (!function_exists('msg_success')) {

    /**
     * 成功时弹出层提示信息
     * @param string $msg 提示信息
     * @param string $url 跳转链接
     * @param int $time 停留时间 默认2秒
     * @param int $icon 提示图标
     * @return string
     */
    function msg_success($msg = '', $url = '', $time = 3, $icon = 1)
    {
        return alert($msg, $url, $time, $icon);
    }

}

if (!function_exists('msg_error')) {

    /**
     * 失败时弹出层提示信息
     * @param string $msg 提示信息
     * @param string $url 跳转链接
     * @param int $time 停留时间 默认2秒
     * @param int $icon 提示图标
     * @return string
     */
    function msg_error($msg = '', $url = '', $time = 3, $icon = 2)
    {
        return alert($msg, $url, $time, $icon);
    }

}

if (!function_exists('clear_menu')) {

    /**
     * 清空菜单缓存
     */
    function clear_menu()
    {
        Cache::clear('menu');
    }

}


if (!function_exists('clear_basic')) {

    /**
     * 清空菜单缓存
     */
    function clear_basic()
    {
        Cache::clear('basic');
    }

}

if (!function_exists('get_ip')) {

    /**
     * 获取用户ip地址
     * @return array|false|string
     */
    function get_ip()
    {
        $ip = false;
        if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
            $ip = $_SERVER["HTTP_CLIENT_IP"];
        }
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
            $ips = explode(", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
            if ($ip) {
                array_unshift($ips, $ip);
                $ip = false;
            }
            for ($i = 0; $i < count($ips); $i++) {
                if (!eregi("^(10│172.16│192.168).", $ips[$i])) {
                    $ip = $ips[$i];
                    break;
                }
            }
        }
        return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
    }

}

if (!function_exists('get_location')) {

    /**
     * 根据ip获取地理位置
     * @param string $ip
     * @return mixed
     */
    function get_location($ip = '')
    {
        empty($ip) && $ip = get_ip();
        $url = "http://ip.taobao.com/service/getIpInfo.php?ip={$ip}";
        $ret = file_get_contents($url);
        $arr = json_decode($ret, true);
        return $arr['data'];
    }

}

if (!function_exists('install_substring')) {

    /**
     * 格式化安装配置信息
     * @param     $str
     * @param     $lenth
     * @param int $start
     * @return string
     */
    function install_substring($str, $lenth, $start = 0)
    {
        $len = strlen($str);
        $r = [];
        $n = 0;
        $m = 0;

        for ($i = 0; $i < $len; $i++) {
            $x = substr($str, $i, 1);
            $a = base_convert(ord($x), 10, 2);
            $a = substr('00000000 ' . $a, -8);

            if ($n < $start) {
                if (substr($a, 0, 1) == 0) {

                } elseif (substr($a, 0, 3) == 110) {
                    $i += 1;
                } elseif (substr($a, 0, 4) == 1110) {
                    $i += 2;
                }
                $n++;
            } else {
                if (substr($a, 0, 1) == 0) {
                    $r[] = substr($str, $i, 1);
                } elseif (substr($a, 0, 3) == 110) {
                    $r[] = substr($str, $i, 2);
                    $i += 1;
                } elseif (substr($a, 0, 4) == 1110) {
                    $r[] = substr($str, $i, 3);
                    $i += 2;
                } else {
                    $r[] = ' ';
                }
                if (++$m >= $lenth) {
                    break;
                }
            }
        }
        return join('', $r);
    }

}

if (!function_exists('parse_sql')) {

    /**
     * 格式化导入的sql语句
     * @param string $sql
     * @param int $limit
     * @return array|string
     */
    function parse_sql($sql = '', $limit = 0)
    {
        if ($sql != '') {
            // 纯sql内容
            $pure_sql = [];

            // 多行注释标记
            $comment = false;

            // 按行分割，兼容多个平台
            $sql = str_replace(["\r\n", "\r"], "\n", $sql);
            $sql = explode("\n", trim($sql));

            // 循环处理每一行
            foreach ($sql as $key => $line) {
                // 跳过空行
                if ($line == '') {
                    continue;
                }

                // 跳过以#或者--开头的单行注释
                if (preg_match("/^(#|--)/", $line)) {
                    continue;
                }

                // 跳过以/**/包裹起来的单行注释
                if (preg_match("/^\/\*(.*?)\*\//", $line)) {
                    continue;
                }

                // 多行注释开始
                if (substr($line, 0, 2) == '/*') {
                    $comment = true;
                    continue;
                }

                // 多行注释结束
                if (substr($line, -2) == '*/') {
                    $comment = false;
                    continue;
                }

                // 多行注释没有结束，继续跳过
                if ($comment) {
                    continue;
                }

                // sql语句
                array_push($pure_sql, $line);
            }

            // 只返回一条语句
            if ($limit == 1) {
                return implode($pure_sql, "");
            }

            // 以数组形式返回sql语句
            $pure_sql = implode($pure_sql, "\n");
            $pure_sql = explode(";\n", $pure_sql);
            return $pure_sql;
        } else {
            return $limit == 1 ? '' : [];
        }
    }

}

if (!function_exists('curl')) {

    /**
     * 模拟请求
     * @return \app\common\service\CurlService
     */
    function curl()
    {
        return new \tool\Curl();
    }

}

/**
 * 生成密码
 * @param  [type] $password      [密码]
 */
function setPassword($password)
{
    if ($password) {
        $data = array();
        $chars = "0123456789";
        $str = "";
        for ($i = 0; $i < 8; $i++) {
            $str .= substr($chars, mt_rand(1, strlen($chars) - 1), 1);
        }
        $data['strict'] = $str;
        $data['password'] = md5(md5($password) . $data['strict']);
        return $data;
    } else {
        return false;
    }
}

//验证密码是否合法
function checkPwd($str)
{
    $model = '/[A-Z]+[a-z]+.*/'; //最少要包含一个或者多个大写或者小写，和0个或则多个任意字符;
    $modelength = '/.{8,}/'; //输入的最少为8位
    if (!preg_match($model, $str) || !preg_match($modelength, $str)) {

    }
}

// 时间转换
function dateTime($time)
{
    return date('Y-m-d H:i:s', $time);
}

/**
 * layui table数据 -API返回
 * @param int $code 返回码 0成功 1失败
 * @param string $msg 提示消息
 * @param array $count 总数量
 * @param array $info ['limit' => $limit, 'page_current' => $page, 'page_sum'  => ceil($count / $limit)] 分页信息【每页条数，当前页数，总页数】
 * @param array $data 数据
 * @return type
 */
function returnJson($code = 0, $msg = '获取成功', $data = [], $count = -1, $info = [])
{
    header('Content-Type:application/json; charset=utf-8');
    if ($count < 0) {
        $list = ['code' => $code, 'msg' => $msg, 'data' => $data];
    } else {
        $list = ['code' => $code, 'msg' => $msg, 'data' => $data, 'count' => $count, 'info' => $info];
    }

    exit(json_encode($list));
}
/**
 * 返回结果
 * @param int $code
 * @param string $message
 * @param array $data
 */
function returnResult(int $code, $message = '', $data = [])
{

    $return['code'] = $code;
    $return['msg'] = $message;
    $return['data'] = $data;
    return $return;
}

/**
 * 处理钱的格式 元转成分 ，分转成元
 * 元转分 formatMoney（$money,1）
 * 分转成元 formatMoney（$money,2)
 * @param int $money 钱
 * @param int $unit 单位1 是元 2是分
 * @param int $point 小数点位数
 */
function formatMoney($money, $unit = 2, $point = 2)
{
    if (empty($money)) {
        return 0;
    }
    if ($unit == 1) {//将元转成分
        $money = round($money * 100);
    } else {
        $reg = '/^[0-9][0-9]*$/';
        $money = $money / 100; //将分转成元
        if ($point == 0 || preg_match($reg, $money)) {
            $money = (int)$money;
        } else {
            $money = sprintf('%.' . $point . 'f', $money);
        }
    }
    return $money;
}

/**
 * 生成订单号
 */
function order_sn()
{
    return strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));
}

/**
 * 验证手机号是否正确
 *
 * @param INT $mobile
 * @return bool
 * @author
 *
 */
function isMobile($mobile)
{
    return preg_match('#^1[3-9][\d]{9}$#', $mobile) ? true : false;
}

/**
 * 同时验证移动号和座机号
 *
 * @param INT $mobile
 * @author
 *
 */
function isPhone($phone)
{
    return preg_match('/((\d{11})|^((\d{7,8})|(\d{4}|\d{3})-(\d{7,8})|(\d{4}|\d{3})-(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1})|(\d{7,8})-(\d{4}|\d{3}|\d{2}|\d{1}))$)/', $phone) ? true : false;
}

/**
 * 验证是否为邮箱
 * @param  [type] $email [description]
 * @return [type]        [description]
 */
function inge_isemail($email)
{
    $pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
//    if (preg_match("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+", $email)) {
    if (preg_match($pattern, $email)) {
        return true;
    } else {
        return false;
    }
}

/**
 * @param $url    地址
 * @param $param  参数json格式
 * @param bool $post_file 是否文件上传
 * @return bool|mixed
 */
function http_post($url, $param, $post_file = false,$headers="")
{
    $oCurl = curl_init();
    if (stripos($url, "https://") !== FALSE) {
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); // CURL_SSLVERSION_TLSv1
    }
    if (is_string($param) || $post_file) {
        $strPOST = $param;
    } else {
        $aPOST = array();
        foreach ($param as $key => $val) {
            $aPOST[] = $key . "=" . urlencode($val);
        }
        $strPOST = join("&", $aPOST);
    }
    curl_setopt($oCurl, CURLOPT_URL, $url);
    curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($oCurl, CURLOPT_POST, true);
    curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
    if(!empty($headers)){
        curl_setopt($oCurl, CURLOPT_HTTPHEADER, $headers);
    }
    $sContent = curl_exec($oCurl);
    $aStatus = curl_getinfo($oCurl);
    curl_close($oCurl);

    if (intval($aStatus["http_code"]) == 200) {
        return json_decode($sContent, true);
    } else {
        return false;
    }
}

/**  YSF
 *   手机号码中间位数隐藏
 * @param $str
 * @return mixed
 */
function yc_phone($str)
{
    $str = $str;
    $resstr = substr_replace($str, '****', 3, 4);
    return $resstr;
}

/**
 * 传递参数 生成编号
 * @param string $head
 * @return string
 */
function pay_sn($head)
{
    return $head . date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}

/**
 * 路径拼接
 * @param String $url
 */
function UploadImgPath($url)
{
    if (empty($url)) {
        return "";
    }
    $str = "http://";
    $strs = "https://";
    if (strpos($url, $str) === false && strpos($url, $strs) === false) {
        $url = config('api.qi_niu_url') . $url;
    }
    return $url;
}

//生成唯一标识uuid
function createUuid()
{
    if (function_exists('com_create_guid')) {
        return com_create_guid();
    } else {
        mt_srand((double)microtime() * 10000); // optional for php 4.2.0 and up.
        $charid = strtoupper(md5(uniqid(rand(), true)));
        $hyphen = chr(45); // "-"
        $uuid = substr($charid, 0, 8) . $hyphen . substr($charid, 8, 4) . $hyphen . substr($charid, 12, 4) . $hyphen . substr($charid, 16, 4) . $hyphen . substr($charid, 20, 12);
        return $uuid;
    }
}


/*
 * 身份证校验、并截取生日(15 or 18)
 * @ligang
 * @return  bool
 */

function checkIdCard($idCard)
{
    $result = preg_match('/^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X|x)$/', $idCard);
    if ($result) {
        return true;
    } else {
        return false;
    }
}
//二维数组查找某一个值，并返回
function searchArray($array, $key1, $value1, $key2 = "", $value2 = "")
{
    $arr = array();
    foreach ($array as $keyp => $valuep) {
        if (empty($key2) || empty($value2)) {
            if ($valuep[$key1] == $value1) {
                array_push($arr, $valuep);
            }
        } else if (empty($key1) || empty($value1)) {
            if ($valuep[$key2] == $value2) {
                array_push($arr, $valuep);
            }
        } else {
            if ($valuep[$key1] == $value1 && $valuep[$key2] == $value2) {
                array_push($arr, $valuep);
            }
        }
    }
    return $arr;
}






